import path from 'path'
import { asyncRoutes, constantRoutes } from '@/router'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => role.roleType <= route.meta.roles)
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, userInfo, basePath = '/') {
  const res = []
  const roles = [userInfo.role]
  console.log('666', userInfo)
  const permissions = userInfo.permissions.map(p => p.menuId)
  routes.forEach(route => {
    if (route.hidden) return
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      const routerPath = path.resolve(basePath, route.path)
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, userInfo, routerPath)
      }
      const haveChildren = tmp.children && tmp.children.length > 0
      if (haveChildren || permissions.includes(routerPath)) {
        res.push(tmp)
      }
    }
  })
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat([])
  }
}

const actions = {
  generateRoutes({ commit }, userInfo) {
    return new Promise(resolve => {
      let accessedRoutes = []
      // const roles = [userInfo.role]
      // if (roles.some(role => role.roleType < 1)) {
      //   accessedRoutes = asyncRoutes || []
      // } else {
      //   accessedRoutes = filterAsyncRoutes(asyncRoutes, userInfo)
      // }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
